package com.jiankang.askhealth.taglibs;

import java.io.IOException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;
import org.apache.struts2.components.Component;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;

import com.opensymphony.xwork2.util.ValueStack;


public class Pages extends Component {

    private HttpServletRequest request;
    private String pageIndex; // 当前页码
    private String total; // 总记录数
    private String pageSize;// 每页最大显示数
    private String styleClass; // 分页的样式
    private String theme; // 分页的主题
    private String url; // action的路径
    private String urlType; // 路径的类型，主要用于URL重写的扩展
    private String method; //提交方式 post|get

    public Pages(ValueStack arg0, HttpServletRequest request) {
        super(arg0);
        this.request = request;
    }

    @Override
    public boolean end(Writer writer, String body) {
        boolean result = super.start(writer);
        try {
            // 从ValueStack中取出数值
            Object obj = this.getStack().findValue(pageIndex);
            pageIndex = String.valueOf((Integer)obj);
            obj = this.getStack().findValue(pageSize);
            pageSize = String.valueOf((Integer)obj);
            obj = this.getStack().findValue(total);
            total = String.valueOf((Integer)obj);
            
            if (Integer.parseInt(total) == 0) {
                return result;
            }
            
            int pageTotal = Integer.parseInt(total) / Integer.parseInt(pageSize);
            if (Integer.parseInt(total) % Integer.parseInt(pageSize) != 0) {
                pageTotal++;
            }
            if (pageTotal <= 1) {
                return result;
            }
            
            StringBuilder divBuilder = new StringBuilder();
            Map stackContext = this.getStack().getContext();
            StrutsRequestWrapper req = (StrutsRequestWrapper) stackContext.get(StrutsStatics.HTTP_REQUEST);
            if (url == null || "".equals(url)) {
                url = (String) req.getAttribute("javax.servlet.forward.request_uri");
            }
            
            if ("get".equals(method)) {
                divBuilder.append("<table width='100%' cellspacing='0' cellpadding='0' border='0' align='center' class='right-font08'><tbody><tr>");
                divBuilder.append("<td width='50%'>共 <span class='right-text09'>").append(pageTotal).append("</span> 页| 第 <span class='right-text09'>").append(pageIndex).append("</span> 页</td>");
                Map params = request.getParameterMap();
                
                StringBuilder paramBuilder = new StringBuilder();
                List<String> ignoreParams = null; 
                if ( this.getParameters().size() != 0 ) {
                    Iterator iter = this.getParameters().keySet().iterator();
                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        Object o = this.getParameters().get(key);
                        if ("ignoreParams".equals(key)) {
                            ignoreParams = Arrays.asList(o.toString().split("\\|"));
                        } else {
                            if (paramBuilder.length() > 0) {
                                paramBuilder.append("&");
                            }
                            paramBuilder.append(key).append("=").append(o);
                        }

                    }

                }
                
                if (params.size() != 0) {
                    Iterator iter = params.keySet().iterator();
                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        if (ignoreParams != null && ignoreParams.contains(key)) {
                            continue;
                        }
                        String[] values = (String[])params.get(key);
                        String value = values[0];
                        if (value != null && value.length()> 0 && !"pageIndex".equals(key)) {
                            if (paramBuilder.length() > 0) {
                                paramBuilder.append("&");
                            }
                            paramBuilder.append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
                        } 
                    }
                }
                
                int nPageIndex = Integer.parseInt(pageIndex);
                String disable = "";
                int prePageIndex = nPageIndex - 1;
                if (paramBuilder.length() != 0) {
                    if (url.indexOf("?") != -1) {
                        url += "&" + paramBuilder.toString();
                    } else {
                        url += "?" + paramBuilder.toString();
                    }
                }
                if (url.indexOf("?") != -1) {
                    url += "&pageIndex=";
                } else {
                    url += "?pageIndex=";
                }
                divBuilder.append("<td width='49%' align='right'>");
                divBuilder.append("[<a class='right-font08' href='").append(url + 1).append("' class='right-font08'>首页</a> | ");
                if(nPageIndex > 1) {
                    divBuilder.append("<a href='").append(url + (nPageIndex - 1)).append("' class='right-font08'>上一页</a>");
                }
                
                String current = "";
                if (1 == nPageIndex) {
                    current = "class='current'";
                } 
                int start = nPageIndex - 1;
                start = Math.min(start, pageTotal - 5);
                start = Math.max(start, 2);
                
                int end = start + 4;
                end = Math.min(end, pageTotal - 1);
                if (start > 2) {
                    divBuilder.append("<span>...</span>");
                }
                for(int i = start; i <= end; i++) {
                    current = "";
                    if (i == nPageIndex) {
                        current = "class='current'";
                    }
                    divBuilder.append("<a ").append(current).append("class='right-font08' title='第"+i+"页' href='"+url + i +"'>"+i+"</a>");
                }
                if (end < pageTotal - 1) {
                    divBuilder.append("<span>...</span>");
                }
                
                if (pageTotal > 1) {
                    current = "";
                    if (pageTotal == nPageIndex) {
                        current = "class='current'";
                    }
                    divBuilder.append("<a ").append(current).append("class='right-font08' title='第"+pageTotal+"页' href='"+url + pageTotal +"'>"+pageTotal+"</a>");
                }
                disable = "";
                int nextPageIndex = nPageIndex + 1;
                if (nPageIndex < pageTotal) {
                    divBuilder.append("<a title='下一页' href='" + url + nextPageIndex + "' class='right-font08'>下一页</a> | ");
                }
                divBuilder.append("<a class='right-font08' href='" + url + pageTotal + "'>末页</a>]</td> ");
                divBuilder.append("</tr></tbody></table></td>");
                
                
            } else {
                
    //            divBuilder.append("<br/>");
                long timestamp = (new Date()).getTime();
                String pageFormId = "pagerFormId" + timestamp;
                divBuilder.append("<form action='").append(url).append("' method='post'").append(" id='").append(pageFormId).append("'>");
                if(styleClass != null){
                	divBuilder.append("<div class='" + styleClass + "'>");
                }
                else{
                	divBuilder.append("<div class='-page tcenter'>");
                }
                
                if ( this.getParameters().size() != 0 ) {
                    Iterator iter = this.getParameters().keySet().iterator();
                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        Object o = this.getParameters().get(key);
                        divBuilder.append("<input type='hidden' name='").append(key).append("' value='").append(o).append("'>");

                    }

                }
                
                Map params = request.getParameterMap();
                if (params.size() != 0) {
                    Iterator iter = params.keySet().iterator();
                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        String[] values = (String[])params.get(key);
                        String value = values[0];
                        if (value != null && value.length()> 0 && !"pageIndex".equals(key)) {
                        	divBuilder.append("<input type='hidden' name='").append(key).append("' value='").append(value).append("'>");
                        } 
                    }
                }
                int nPageIndex = Integer.parseInt(pageIndex);
                String pageIndexId = "pageIndexId" + timestamp;
                divBuilder.append("<input type='hidden' name='pageIndex' id='").append(pageIndexId).append("'>");
                String disable = "";
                int prePageIndex = nPageIndex - 1;
                if (nPageIndex == 1) {
                    disable = "class='p-none'";
                } else {
                    disable = "onclick='changePage("+prePageIndex+");return false;'";
                }
                divBuilder.append("<a href='javascript:void(0)' class='prevPage' "+disable+">«</a>");
    //            divBuilder.append("<a title='第1页' href='javascript:void(0)' class='current'>1</a>");
                
                
                String current = "";
                if (1 == nPageIndex) {
                    current = "class='current'";
                } 
                divBuilder.append("<a ").append(current).append(" title='第1页' href='javascript:void(0)' onclick='changePage(1);return false;'>1</a>");
                int start = nPageIndex - 1;
                start = Math.min(start, pageTotal - 5);
                start = Math.max(start, 2);
                
                int end = start + 4;
                end = Math.min(end, pageTotal - 1);
                if (start > 2) {
                    divBuilder.append("<span>...</span>");
                }
                for(int i = start; i <= end; i++) {
                    current = "";
                    if (i == nPageIndex) {
                        current = "class='current'";
                    }
                    divBuilder.append("<a ").append(current).append(" title='第"+i+"页' href='javascript:void(0)' onclick='changePage("+i+");return false;'>"+i+"</a>");
                }
                if (end < pageTotal - 1) {
                    divBuilder.append("<span>...</span>");
                }
                
                if (pageTotal > 1) {
                    current = "";
                    if (pageTotal == nPageIndex) {
                        current = "class='current'";
                    }
                    divBuilder.append("<a ").append(current).append(" title='第"+pageTotal+"页' href='javascript:void(0)' onclick='changePage("+pageTotal+");return false;'>"+pageTotal+"</a>");
                }
                disable = "";
                int nextPageIndex = nPageIndex + 1;
                if (nPageIndex == pageTotal) {
                    disable = "class='p-none'";
                } else {
                    disable = "onclick='changePage("+nextPageIndex+");return false;'";
                }
                divBuilder.append("<a title='下一页' "+disable+" href='javascript:void(0)' class='nextPage'>»</a>");
                divBuilder.append("</div>");
                divBuilder.append("</form>").append("\n");
                
                divBuilder.append("<script type=\"text/javascript\">").append("\n");
                divBuilder.append("function changePage(index) {").append("\n");
                divBuilder.append("$(\"#").append(pageIndexId).append("\").val(index);").append("\n");
                divBuilder.append("$(\"#").append(pageFormId).append("\").submit();").append("\n");
                divBuilder.append("return false;").append("\n");
                divBuilder.append("}").append("\n");
                divBuilder.append("</script>");
            }
            

            writer.write(divBuilder.toString());

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String getStyleClass() {
        return styleClass;
    }

    public void setStyleClass(String styleClass) {
        this.styleClass = styleClass;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlType() {
        return urlType;
    }

    public void setUrlType(String urlType) {
        this.urlType = urlType;
    }

    public String getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(String pageIndex) {
        this.pageIndex = pageIndex;
    }

    public String getPageSize() {
        return pageSize;
    }

    public void setPageSize(String pageSize) {
        this.pageSize = pageSize;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

}
